import copy

from django.http import QueryDict
from django.template import Library
from django.conf import settings
from django.urls import reverse
from django.utils.safestring import mark_safe

register = Library()


def check_permission(request, name):
    # 获取当前登录用户的角色
    role = request.nb_user.role
    # 根据角色获取他所有的权限字典
    permission_dict = settings.NB_PERMISSION[role]
    # 在权限里
    if name in permission_dict:
        return True

    if name in settings.NB_PERMISSION_PUBLIC:
        return True

@register.simple_tag
def add_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""

    # 有权限 则 通过"customer_add"  反向生成URL
    url = reverse(name, args=args, kwargs=kwargs)
    tpl = """
        <a class="btn btn-success" href="{}">
            <span class="glyphicon glyphicon-plus-sign"></span> 新建
        </a>
        """.format(url)
    return mark_safe(tpl)


@register.simple_tag
def edit_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""
    # 无权限，返回空
    # 有权限 则 通过"customer_add"  反向生成URL
    # /customer/edit/666/
    url = reverse(name, args=args, kwargs=kwargs)
    # 根据当前用户请求获取GET参数
    param = request.GET.urlencode()
    if param:
        new_query_dict = QueryDict(mutable=True) # page=8&xxx=123
        new_query_dict['_filter'] = param
        filter_string = new_query_dict.urlencode()

        tpl = """
            <a class="btn btn-primary btn-xs" href="{}?{}">编辑</a>""".format(url, filter_string)
        return mark_safe(tpl)
    # 此时不带_filter
    tpl = """
                <a class="btn btn-primary btn-xs" href="{}">编辑</a> """.format(url)
    return mark_safe(tpl)

@register.simple_tag
def delete_url_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""
    # 无权限，返回空
    # 有权限 则 通过"customer_add"  反向生成URL

    url = reverse(name, args=args, kwargs=kwargs)
    tpl = """
        <a href="{}" class="btn btn-danger btn-xs btn-delete">删除</a>
        """.format(url)
    return mark_safe(tpl)

@register.simple_tag
def delete_permission(request, name, *args, **kwargs):
    if not check_permission(request, name):
        return ""
    # 无权限，返回空
    # 有权限 则 通过"customer_add"  反向生成URL
    # 此处不用返向生成url
    pk = kwargs.get('pk')
    tpl = """
        <a cid="{}" class="btn btn-danger btn-xs btn-delete">删除</a>
        """.format(pk)
    return mark_safe(tpl)

@register.filter
def has_permission(request,  others):
    name_list = others.split(',')
    for name in name_list:
        status = check_permission(request, name)
        if status:
            return True
    return False

